/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.yoyo.fragment.reading;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.fcat.base.common.util.DateUtil;
import com.fcat.base.common.util.StrUtil;
import com.xuexiang.yoyo.adapter.ReadDataRecyclerAdapter;
import com.xuexiang.yoyo.adapter.entity.ReadData;
import com.xuexiang.yoyo.core.BaseFragment;
import com.xuexiang.yoyo.databinding.FragmentQueryReadingBinding;
import com.xuexiang.yoyo.entity.DataItemLatest;
import com.xuexiang.yoyo.entity.ProfileGeneric;
import com.xuexiang.yoyo.entity.ProfileGenericData;
import com.xuexiang.yoyo.entity.ProfileGenericObject;
import com.xuexiang.yoyo.sql.mapper.DataItemLatestMapper;
import com.xuexiang.yoyo.sql.mapper.ProfileGenericDataMapper;
import com.xuexiang.yoyo.sql.mapper.ProfileGenericMapper;
import com.xuexiang.yoyo.sql.mapper.ProfileGenericObjectMapper;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.grouplist.XUIGroupListView;

import java.util.Date;
import java.util.List;

/**
 * @author liuxiangfei
 * @since 2023-07-24 00:19
 */
@Page(anim = CoreAnim.none)
public class QueryReadingFragment extends BaseFragment<FragmentQueryReadingBinding> {
    private ReadDataRecyclerAdapter mAdapter;
    @NonNull
    @Override
    protected FragmentQueryReadingBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentQueryReadingBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle().setTitle("查询");
        titleBar.addAction(
                new TitleBar.TextAction("设置"){

                    @Override
                    public void performAction(View view) {
                        XToastUtils.toast("点击测试");
                    }
                }
        );
        return titleBar;
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        initNotConnectView();

        initEnableBt();


        binding.ScrollView01.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                binding.ScrollView01.post(new Runnable() {
                    public void run() {
                        binding.ScrollView01.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        });


        WidgetUtils.initRecyclerView(binding.recyclerView);
        binding.recyclerView.setAdapter(mAdapter = new ReadDataRecyclerAdapter());
        mAdapter.setOnItemClickListener((itemView, item, position) -> {
            XToastUtils.toast("position: " +position+"  item:"+item.getDataItemName());
        });
    }


    private void initEnableBt() {
        binding.enableBt.setOnClickListener(v -> {
            binding.notConnectView.setVisibility(View.VISIBLE);
            mAdapter.clear();
            loadData();
        });
    }

    private void initNotConnectView() {
        binding.notConnectView.setVisibility(View.GONE);
        int size = DensityUtils.dp2px(getContext(), 20);
        XUIGroupListView.newSection(getContext()).setTitle("查询学习数据")
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addTo(binding.notConnectView);
    }
    private void loadData() {
        String deviceCode = binding.etMeterCoder.getText().toString();
        List<DataItemLatest> dataItemLatests = DataItemLatestMapper.queryByDeviceCode(deviceCode);
        for(DataItemLatest dataItemLatest:dataItemLatests){
            mAdapter.add(new ReadData(dataItemLatest.getDataItemName(),dataItemLatest.getValue()+(dataItemLatest.getUnit()==null?"":dataItemLatest.getUnit()),dataItemLatest.getLn()));
            binding.recyclerView.scrollToPosition(mAdapter.getItemCount()-1);
        }

        List<ProfileGeneric> profileGenerics = ProfileGenericMapper.queryByDeviceCode(deviceCode);
        for(ProfileGeneric profileGeneric:profileGenerics){
            List<ProfileGenericObject> profileGenericObjects = ProfileGenericObjectMapper.queryByDeviceCode(deviceCode,profileGeneric.getChannelLn());

            mAdapter.add(new ReadData(profileGeneric.getName()+"(Entries In Use)",profileGeneric.getEntriesInUse()+"",profileGeneric.getChannelLn()));
            binding.recyclerView.scrollToPosition(mAdapter.getItemCount()-1);

            mAdapter.add(new ReadData(profileGeneric.getName()+"(Profile Entries)",profileGeneric.getProfileEntries()+"",profileGeneric.getChannelLn()));
            binding.recyclerView.scrollToPosition(mAdapter.getItemCount()-1);

            String objects = "";
            for(int i=0;i<profileGenericObjects.size();i++){
                ProfileGenericObject profileGenericObject = profileGenericObjects.get(i);
                objects += profileGenericObject.getLn();
                if(i!=0){
                    objects += "("+profileGenericObject.getScaler()+profileGenericObject.getUnit()+")";
                }

                if(i!=profileGenericObjects.size()-1){
                    objects += ",";
                }
            }
            if(!StrUtil.isBlank(objects)){
                mAdapter.add(new ReadData(profileGeneric.getName()+"(Objects)",objects,profileGeneric.getChannelLn()));
                binding.recyclerView.scrollToPosition(mAdapter.getItemCount()-1);
            }

            List<ProfileGenericData> profileGenericDatas = ProfileGenericDataMapper.queryByDeviceCode(deviceCode, profileGeneric.getChannelLn());
            for(int i=0;i<profileGenericDatas.size();i++){
                ProfileGenericData profileGenericData = profileGenericDatas.get(i);
                String values = DateUtil.formatDate(new Date(profileGenericData.getClockTime()),DateUtil.TIME_PATTERN_DISPLAY)+"," + profileGenericData.getValue();

                mAdapter.add(new ReadData(profileGeneric.getName()+"(Data-"+(i+1)+")",values,profileGeneric.getChannelLn()));
                binding.recyclerView.scrollToPosition(mAdapter.getItemCount()-1);
            }
        }




/*        mAdapter.add(new ReadData("Maximum Demand Import kW (last reset)","00000.000kW",""));
        mAdapter.add(new ReadData("Total Import Active Maximum Demand","11/30/02 12:00:00 AM",""));
        mAdapter.add(new ReadData("T4 Import Active Maximum Demand","ER03",""));
        mAdapter.add(new ReadData("Nominal Frequency","60Hz",""));
        mAdapter.add(new ReadData("Monthly BIlling 1(Objects)","Clock Object,Total Absolute Sum Acitve Energy,T1 Absolute Sum Acitve Energy,T2 Absolute Sum Acitve Energy,T3 Absolute Sum Acitve Energy,T4 Absolute Sum Acitve Energy,Total Import Acitve Energy,T1 Import Acitve Energy,T2 Import Acitve Energy,T3 Import Acitve Energy,T4 Import Acitve Energy,Total Export Active Energy,T1 Export Active Energy,T2 Export Active Energy,T3 Export Active Energy,T4 Export Active Energy,Total Import Reactive Energy,T1 Import Reactive Energy,T2 Import Reactive Energy,T3 Import Reactive Energy,T4 Import Reactive Energy,Total Export Reactive Energy,T1 Export Reactive Energy,T2 Export Reactive Energy,T3 Export Reactive Energy,T4 Export Reactive Energy",""));
        mAdapter.add(new ReadData("Monthly BIlling 1(entriesInUse)","3",""));
        mAdapter.add(new ReadData("Monthly BIlling 1(Datas-1)","2021-01-15 20:00:01,110190.0,110190.0,0.0,0.0,0.0,110190.0,110190.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,41500.0,41500.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0",""));
        mAdapter.add(new ReadData("Monthly BIlling 1(Datas-2)","2023-07-25 20:00:01,93460.0,93460.0,0.0,0.0,0.0,93460.0,93460.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,34310.0,34310.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0",""));
        mAdapter.add(new ReadData("Monthly BIlling 1(profileEntries)","13",""));*/
        binding.recyclerView.scrollToPosition(mAdapter.getItemCount()-1);

    }


}
